package com.bwie.task;

import bwie.pojo.Goods;
import bwie.pojo.Image;
import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.GoodsEs;
import com.bwie.service.GoodsService;
import com.bwie.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class TaskGoods {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ImageService imageService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void task(){
        System.out.println("开启同步");
        List<Goods> goods = goodsService.pageList();
        List<Image> images = imageService.list();
        for (Goods good : goods){
            ArrayList<Image> list = new ArrayList<>();
            for (Image image : images) {
                if (image.getGoodsId() == good.getId());
                list.add(image);
            }
            good.setImageList(list);
            GoodsEs goodsEs = BeanUtil.toBean(goods, GoodsEs.class);
            elasticsearchRestTemplate.save(goodsEs);
        }
        System.out.println("关闭同步");
    }

}
